﻿using MQTTnet;
using System.Text;

namespace Leo.Common.MQTT
{
    /// <summary>
    /// MQTT 连接
    /// </summary>
    public class MQTTConnection : IDisposable
    {
        private IMqttClient _client;
        private readonly MQTTConfig _config;
        public MQTTConnection(MQTTConfig config)
        {
            this._config = config;

            _ = Init();
        }

        private async Task Init()
        {
            await GetMqttClientAsync();
        }

        /// <summary>
        /// 获取MQTT客户端实例
        /// </summary>
        /// <returns></returns>
        public async Task<IMqttClient> GetMqttClientAsync()
        {
            if (_client == null || !_client.IsConnected)
            {
                _client = await CreateConnectionAsync();
            }
            return _client;
        }

        /// <summary>
        /// 创建连接
        /// </summary>
        /// <returns></returns>
        private async Task<IMqttClient> CreateConnectionAsync()
        {
            //创建MQTT客户端工厂，用于创建MQTT客户端实例
            var mqttFactory = new MqttClientFactory();
            //通过工厂创建MQTT客户端
            var mqttClient = mqttFactory.CreateMqttClient();

            // 使用建造者模式创建MQTT客户端连接选项
            var option = new MqttClientOptionsBuilder()
                 .WithTcpServer(_config.Host, _config.Port)  //设置MQTT 服务器 地址和端口
                 .WithProtocolVersion((MQTTnet.Formatter.MqttProtocolVersion)_config.MqttVersion)
                 .WithCleanSession()   // 设置 清洁会话（不保留历史会话状态） 
                 .WithClientId(_config.ClientId)   // 设置客户端唯一标识
                 .Build();   //  构建配置选项对象

            // 使用 配置的选项 连接 MQTT服务器
            await mqttClient.ConnectAsync(option);

            // 检查客户端 是否连接成功
            if (!mqttClient.IsConnected)
            {
                await Console.Out.WriteLineAsync("MQTT 客户端连接失败");
            }

            return mqttClient;
        }


        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}
